/*
 * @Author: luoqi
 * @Date: 2022-03-28 18:48:01
 * @LastEditors: luoqi
 * @LastEditTime: 2022-04-27 16:37:57
 * @Description: 
 */
import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Space, Table, Popconfirm, message } from 'antd';
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';

import Addclassify from './AddClassify';
import Modifyclassify from './ModifyClassify'

import axios from '../../utils/axios'
import qs from 'qs'

import { getTypeListAsync } from '../../store/preTypeAction'
import { connect } from 'react-redux'


const Allclassify = (props) => {
  const {departmentTree,partTree} = props.types;
  let [pag, setPag] = useState({ defaultCurrent: 1, pageSize: 5, current: 1, showTotal: total => `共 ${total} 条`, onChange: changePage })
  let [form]=Form.useForm()
  let [data, setData] = useState() 
  //用于触发重新渲染页面
  let [num, setNum] = useState(0)
  //搜索或全部
  let [isAll,setIsAll]=useState(true)
  //所有一级分类
  let typeArr = props.types;
  //页数更改时
  function changePage(page, pageSize) {
    console.log(page, pageSize);
    setPag({ ...pag, current: page, pageSize })
  }

  //页面加载完毕调接口，页数更改时调接口
  useEffect(() => {

    if(isAll){
      axios({
      url: '/classify/selectAll',
      method: 'post',
      data: qs.stringify({
        page: pag.current,
        size: pag.pageSize
      })
    }).then(res => {
      console.log(res);
      if (res.code === '200') {
        setIsAll(true)
        //给每一个加key
        setData(res.data.map(item => ({ ...item, key: item.id })))
        setPag({ ...pag, total: res.count })
        if (num == 1) {
          setNum(0)
        }

      }
    })
    }else{
      form.submit()
    }
    
  }, [pag.current, num,isAll])
  //搜索
  const onFinish = (values) => {
    // console.log('Success:', values);
    if(isAll==true){
      pag.current=1
    }
    axios({
      url: '/classify/selectAll',
      method: 'post',
      data: qs.stringify({
        page: pag.current,
        size: pag.pageSize,
        name:values.classifyName.trim()
      })
    }).then(res => {
      console.log(res);
      if (res.code === '200') {
        setIsAll(false)
        //给每一个加key
        setData(res.data.map(item => ({ ...item, key: item.id })))
        setPag({ ...pag, total: res.count })
        if (num == 1) {
          setNum(0)
        }
      }
    })
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  }
  //删除
  function confirm(obj) {
    // console.log(obj);
    axios({
      url: '/classify/delete',
      method: 'post',
      data: qs.stringify({ ids: obj.id.toString() })
    }).then(res => {
      console.log(res);
      if (res.code == '200') {
        message.success('删除成功');
        setNum(1)
      }
    })

  }

  function cancel(e) {
    // console.log(e);
    // message.error('Click on No');
  }
  const columns = [
    {
      title: '分类名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'icon图片',
      dataIndex: 'iconImg',
      key: 'iconImg',
      render: text => text?<img style={{width:'50px',height:'50px'}} src={text} alt="" />:'暂无'
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: text => (text == true ? '科室' : '部位')
    },
    {
      title: '分类级别',
      dataIndex: 'pid',
      key: 'pid',
      render: text => (text == 0 ? '一级分类' : '二级分类')
    },
    {
      title: '父级分类',
      dataIndex: 'pid',
      key: 'pid',
      render: (text, record) => {
        //判断是否为一级类别
        // console.log(record);
        let obj;
        if (text != 0) {
          if (!record.type) {
            obj = partTree.filter(item => item.id == text)[0]
          } else {
            obj = departmentTree.filter(item => item.id == text)[0]
          }

        }
        return text == 0 ? '无' : obj.name
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: text => (text == true ? '可用' : '不可用')
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <Modifyclassify data={record} setNum={setNum} />
          <Popconfirm
            title="确定要删除该分类吗?"
            onConfirm={() => confirm(record)}
            onCancel={cancel}
            okText="确定"
            cancelText="取消"
          >
            <Button type="primary" ghost>删除</Button>
          </Popconfirm>

        </Space>
      ),
    },
  ];
  return (
    <div>
      <Form
        name="basic"
        form={form}
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 16,
        }}
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Space>
          <Form.Item
            label="分类名称"
            name="classifyName"
            // rules={[
            //   {
            //     required: true,
            //     message: '请输入分类名称!',
            //   },
            // ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType='submit' icon={<SearchOutlined />}>
              查询
            </Button>
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Addclassify setNum={setNum} />
          </Form.Item>
        </Space>
      </Form>
      <Table columns={columns} dataSource={data} pagination={pag} />
    </div>
  );
}

export default connect(
  state => ({ types: state.types }),
  { getTypeListAsync }
)(Allclassify);
